import * as THREE from 'three';
// 计算线段与点之间的距离
export function calculateDistance(pt1: THREE.Vector3, pt2: THREE.Vector3, pt: THREE.Vector3) {
    const egdeV1 = new THREE.Vector3().subVectors(pt2, pt1)
    const egdeV2 = new THREE.Vector3().subVectors(pt, pt1)
  
    // translate to normalize
    const v1Norm = egdeV1.clone().normalize()
    const v2Norm = egdeV2.clone().normalize()
    // calculate the cos@ between vector 1 and vector 2
    const cos1 = v1Norm.dot(v2Norm)
  
    const egdeV3 = new THREE.Vector3().subVectors(pt, pt2)
    const egdeV4 = new THREE.Vector3().subVectors(pt1, pt2)
    const v3Norm = egdeV3.clone().normalize()
    const v4Norm = egdeV4.clone().normalize()
    // calculate the cos@ between vector 1 and vector 2
    const cos2 = v3Norm.dot(v4Norm)
  
    // make sure to angel are less than 90, the distance will be located at red line
    if (cos2 > 0 && cos1 > 0) {
  
      const sin = Math.sqrt(1 - cos1 * cos1)
  
      const yDistance = pt1.distanceTo(pt)
      const distance = yDistance * sin
  
      // calculate target point
      const xDistance = yDistance * cos1
      const dir = egdeV1.clone().normalize().multiplyScalar(xDistance)
      const targetPt = pt1.clone().add(dir)
  
      const warningDir = egdeV1.clone().normalize().multiplyScalar(xDistance + 200)
      const warningPt = pt1.clone().add(warningDir)
  
      return { 'pt1': pt1, 'pt2': pt2, 'pt': pt, 'distance': distance, 'targetPt': targetPt, 'warningPt': warningPt }
    }
  
    return null
  }